import pymysql


# 连接数据库
def get_db(sql, args=()):
    connect = pymysql.connect(
        host='10.10.4.28',
        port=3306,
        user='chinavis',
        passwd='123456',
        db='chinavis_data',
        charset='utf8'
    )
    # 获取游标
    cursor = connect.cursor()
    cursor.execute(sql, args)
    connect.commit()
    rv = cursor.fetchall()
    columns = [col[0] for col in cursor.description]
    # 关闭连接
    cursor.close()
    connect.close()
    # return (rv[0] if rv else None) if one else rv
    return [
        dict(zip(columns, row))
        for row in rv
    ]

#
# connect = pymysql.connect(
#     host='10.10.4.28',
#     port=3306,
#     user='chinavis',
#     passwd='123456',
#     db='chinavis_data',
#     charset='utf8'
#  )
#
# my_db = connect.cursor()

#
# def excute_query(sql, args=()):
#     my_db.execute(sql, args)
#     connect.commit()
#     rv = my_db.fetchall()
#     columns = [col[0] for col in my_db.description]
#     return [
#         dict(zip(columns, row))
#         for row in rv
#     ]


def get_conn(sql, args=()):
    connect = pymysql.connect(
        host='10.10.4.28',
        port=3306,
        user='chinavis',
        passwd='123456',
        db='chinavis_data',
        charset='utf8'
    )
    connect.ping(reconnect=True)
    # 获取游标
    cursor = connect.cursor()
    cursor.execute(sql, args)
    connect.commit()
    rv = cursor.fetchall()
    # 关闭连接
    cursor.close()
    connect.close()
    return rv
